package com.base.hong.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.base.hong.R

/**
 *
 *Create by Hong on 2023/4/13 11:22.
 *
 */
class `3DView`(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private var bitmap: Bitmap? = null // 位图对象
    private var mmatrix = Matrix() // 变换矩阵
    private var camera = Camera() // 相机对象
    private var rotationX = 0f
    private var rotationY = 0f
    private var lastTouchX = 0f
    private var lastTouchY = 0f

    init {
        bitmap = BitmapFactory.decodeResource(resources, R.drawable.icon_head)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(bitmap?.width?:0, bitmap?.height?:0)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            bitmap?.let {
                // 获取位图中心点坐标
                val centerX = it.width / 2f
                val centerY = it.height / 2f

                // 重置矩阵
                mmatrix.reset()

                // 对矩阵进行三维旋转变换
                camera.save() // 保存相机状态
                camera.rotateX(rotationX) // 沿X轴旋转
                camera.rotateY(rotationY) // 沿Y轴旋转
                camera.getMatrix(mmatrix) // 获取相机变换后的矩阵
                camera.restore() // 恢复相机状态
                // 将矩阵中心点移到画布中心
                mmatrix.preTranslate(-centerX, -centerY)
                mmatrix.postTranslate(centerX, centerY)

                // 绘制位图
                canvas.drawBitmap(it, mmatrix, null)
            }}
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchX = event.x
                lastTouchY = event.y
            }
            MotionEvent.ACTION_MOVE -> {
                val dx = event.x - lastTouchX
                val dy = event.y - lastTouchY
                rotationX -= dy
                rotationY += dx
                invalidate()
                lastTouchX = event.x
                lastTouchY = event.y
            }
        }
        return true
    }
}
